package com.wisdytech.common.utils;

import com.wisdytech.common.session.SessionManage;
import com.wisdytech.common.session.UserSession;
import com.wisdytech.common.thrift.dto.ServerDto;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.UUID;

/**
 * <p>
 * Title: MD工具类
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2017
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author xubin
 * @version 1.0
 */

public class BaseUtil {
    /**
     * 
     * <p>
     * Description: 把jsonStr信息写入到response中
     * </p>
     * 
     * @param response 响应
     * @param jsonStr 需要写入的集合
     */
    public static void writeJsonStr(HttpServletResponse response, String jsonStr) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    /**
     * 
     * <p>Description: 获取唯一id</p>
     * @return
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("\\-", "");
    }
    
    /**
     * 
     * <p>Description: 获取用户登陆对象</p>
     * @param currentSession 用户httpSession对象
     * @return 用户对象
     */
    public static UserSession getUserSession(HttpSession currentSession){
        return (UserSession) currentSession.getAttribute(SessionManage.USERSESSION);
    }
    
    /**
     * 
     * <p>Description: 获取用户登陆对象</p>
     * @return 用户对象
     */
    public static SysUser getCurrentUser(){
    	//Session session = SecurityUtils.getSubject().getSession();
    	if(null !=SecurityUtils.getSubject().getPrincipal()) {
    		SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
        	return user;
    	}
    	return null;
    	
    }
    
    /**
     * 
     * <p>Description: 获取用户登陆对象</p>
     * @return 用户对象
     */
    public static Session getCurrentSession(){
    	Session session = SecurityUtils.getSubject().getSession();
    	return session;
    }
    
    /**
     * <p>Description: 得到客户端IP</p>
     * @param request 请求信息
     * @return ip
     * @throws Exception 异常
     */
    public static String getIpAddress(HttpServletRequest request) throws Exception {
        String ipAddress; 
        ipAddress = request.getHeader("X-Forwarded-For");   
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
            ipAddress = request.getHeader("Proxy-Client-IP");   
        }   
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
            ipAddress = request.getHeader("WL-Proxy-Client-IP");   
        }   
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {   
            ipAddress = request.getRemoteAddr();   
            if ("127.0.0.1".equals(ipAddress)) {
                InetAddress inet;  
                inet = InetAddress.getLocalHost();   
                ipAddress = inet.getHostAddress();   
            }  
        }   
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割   
        if (ipAddress != null && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));   
        }
        return ipAddress;
    }
    
    /**
     * 
     * <p>Description: 计算百分比</p>
     * @param b1
     * @param b2
     * @param scale
     * @return
     */
    public static Double divide(Long b1,Long b2,Integer scale){
        if(b1 ==null ||b1==0){
            return 0.00;
        }
        
        BigDecimal b11 = new BigDecimal(b1);
        //除数
        BigDecimal b22 = new BigDecimal(b2);
        
        return b11.divide(b22, scale, BigDecimal.ROUND_HALF_EVEN).doubleValue();
    }
    
    /**
     * 
     * <p>Description: 计算百分比</p>
     * @param b1
     * @param b2
     * @param scale
     * @return
     */
    public static Double divide(Integer b1,Integer b2,Integer scale){
        if(b1 ==null ||b1==0){
            return 0.00;
        }
        
        BigDecimal b11 = new BigDecimal(b1);
        //除数
        BigDecimal b22 = new BigDecimal(b2);
        
        return b11.divide(b22, scale, BigDecimal.ROUND_HALF_EVEN).doubleValue();
    }
    
    
    /**
     * 
     * <p>Description: 保留小数未</p>
     * @param value
     * @return
     */
    public static Double getDecimal(Double value,int scala){
    	if(value == null || value ==0){
    		return 0.00;
    	}
    	
        BigDecimal bg = new BigDecimal(value);
        double f1 = bg.setScale(scala, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }
    
    
    
    
    
    /**
     * 
     * <p>Description: 获取服务地址</p>
     * @param address
     * @return
     */
    public static ServerDto getServerAddress(String address){
        
        if(StringUtils.isBlank(address)){
            return null;
        }
        ServerDto dto =new ServerDto();
        String[]  serverAddress =address.split(":");
        if(serverAddress.length != 2){
            return null;
        }
        dto.setIp(serverAddress[0]);
        dto.setPort(Integer.parseInt(serverAddress[1]));
        
        return dto;
        
    }

    /**
     *
     * <p>Description: 判断是否为ajax请求</p>
     * @param request 请求对象
     * @return boolean
     */
    public static boolean isAjax(HttpServletRequest request){
        if(org.apache.commons.lang3.StringUtils.isBlank(request.getHeader("X-Requested-With"))){
            return false;
        }
        return  "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()) ;
    }


    
}
